package cn.mianshiyi.example.demo;


import cn.mianshiyi.localcache.client.zk.ZkAbstractLocalCache;
import cn.mianshiyi.localcache.client.zk.ZkCacheConfig;
import cn.mianshiyi.localcache.client.zkv2.ZkV2AbstractLocalCache;
import cn.mianshiyi.localcache.client.zkv2.ZkV2CacheConfig;

import javax.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author shangqing.liu
 */
//@Service
public class ZkTestCache extends ZkV2AbstractLocalCache<String, String> {

    @Override
    public String refresh(String key) {
        // 主动刷新缓存逻辑
        return setCache(key, UUID.randomUUID().toString());
    }

    @Override
    public void receive(byte[] data) {
        //接收到消息变更后，查询最新数据取更新本地数据
        String s = String.valueOf(data);
        setCache(s, UUID.randomUUID().toString());
    }

    public static void main(String[] args) throws InterruptedException {
        ZkTestCache orderCancelReasonLocalCache = new ZkTestCache();
        ZkV2CacheConfig config = new ZkV2CacheConfig(10, 1000, 24 * 60 * 60
                , "/test", "127.0.0.1:2181");
        orderCancelReasonLocalCache.init(config);
        AtomicInteger atomicInteger = new AtomicInteger(10);
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    // 模拟数据变更 广播数据
                    orderCancelReasonLocalCache.broadcast(String.valueOf(atomicInteger.getAndAdd(10)).getBytes(StandardCharsets.UTF_8));
                }
            }).start();
        }
        Thread.sleep(100000);
    }

}
